<template>
  <div class="ht-container" v-loading="state.loading">
    <HtHeader :data="breadData">
      <el-button style="margin-top: 4px; " @click="state.visible = true" type=""
        >创建并库计划</el-button
      >
    </HtHeader>
    <OldHtSearch
      @handelVisible="handelVisible"
      placeholder="搜索    并库计划单号"
      @reset="reset"
      :showFilter="true"
      @search="search"
    >
      <el-col :span="6">
        <el-form-item label="创建人">
          <ht-select-user
            placeholder="请输入"
            @change="handleSearch"
            v-model="state.filter.creatorId"
            :clearable="true"
          ></ht-select-user>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item label="创建时间">
          <SelectTimeRange
            :pickerOptions="{
              disabledDate(time) {
                return time.getTime() > Date.now();
              },
            }"
            style="width: 100%; margin-top: 4px"
            v-model="state.filter.timeArr"
            @change="handleSearch"
            :clearable="true"
          ></SelectTimeRange>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="并库状态">
          <el-select
            v-model="state.filter.status"
            :clearable="true"
            @change="handleSearch"
            style="width:100%"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in state.options"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="并库执行顺序">
          <el-select
            v-model="state.filter.isSort"
            :clearable="true"
            @change="handleSearch"
            style="width:100%"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in state.options1"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </OldHtSearch>

    <el-card class="ht-card" style="margin-top: 16px">
      <ht-table
        class="ht-table-no-border"
        :data="state.dataSource"
        @onchange="changePage"
        style="width: 100%; margin-top: 12px"
        border
        pageStyle="text-align:right"
        :height="`calc(100vh - 314px - ${state.searchHeight}px)`"
        highlight-current-row
        :page-info="{
          currentPage: state.filter.currentPage,
          pageSize: state.filter.maxResultCount,
          skipCount: state.filter.skipCount,
          totalCount: state.filter.totalCount,
        }"
        :columns="columns"
      >
        <Temp slot="empty">
          <span slot="tips">暂无数据哦</span>
        </Temp>

        <template slot="statusStr" slot-scope="{ row }">
          <Status :color="status[row.status - 1].color">{{
            row.statusStr
          }}</Status>
        </template>

        <template slot="creatorId" slot-scope="{ row }">
          <ht-select-user v-model="row.creatorId" :readonly="true">
          </ht-select-user>
        </template>

        <template slot="creationTime" slot-scope="{ row }">
          {{ row?.creationTime?.replace('T', ' ').slice(0, 16) }}
        </template>
        <template slot="progress" slot-scope="{ row }">
          {{
            row.progress.unStart +
              '/' +
              row.progress.processing +
              '/' +
              row.progress.complated +
              '/' +
              row.progress.total
          }}
        </template>

        <template slot="header_progress">
          归还要求<tips
            tips="未开始移库酒罐数量/正在处理移库酒罐数量/已完成移库酒罐数量/并库计划酒罐总数"
          ></tips>
        </template>

        <template slot="handel" slot-scope="{ row }">
          <span class="cursor" @click="handDetail(row)">详情</span>

          <ht-popover
            okText="确定结束"
            okType="danger"
            tips="结束并库后，移库工单将无法关联到该并库计划，确定要结束并库吗？"
            @confirm="finish(row)"
            icon-style="color:#D54545;font-size:16px'"
          >
            <span style="margin-left:24px; " class="cursor" slot="reference"
              >结束并库</span
            >
          </ht-popover>
        </template>
      </ht-table></el-card
    >

    <!-- 创建并库计划 -->
    <ht-drawer
      class="ht-new-drawer"
      v-if="state.visible"
      v-model="state.visible"
      title="创建并库计划"
      size="100%"
    >
      <CreateProject ref="createProject"></CreateProject>

      <div slot="foot">
        <!-- 提示 -->
        <el-button
          :loading="state.loading"
          type="primary"
          style="margin-left:24px;margin-right:14px; "
          @click="save"
          >发起并库</el-button
        >

        <el-button :loading="state.loading" @click="state.visible = false"
          >取消</el-button
        >
      </div>
    </ht-drawer>
    <!-- 并库详情 -->
    <ht-drawer
      class="ht-new-drawer"
      v-if="state.visible1"
      v-model="state.visible1"
      title="并库详情"
      size="100%"
    >
      <Detail :selectRow="state.selectRow"></Detail>

      <div slot="foot">
        <ht-popover
          okText="确定结束"
          okType="danger"
          tips="结束并库后，移库工单将无法关联到该并库计划，确定要结束并库吗？"
          @confirm="finish(state.selectRow)"
          icon-style="color:#D54545;font-size:16px'"
        >
          <el-button
            style="margin-left:24px;margin-right:14px; "
            slot="reference"
            >结束并库</el-button
          >
        </ht-popover>

        <el-button :loading="state.loading" @click="state.visible1 = false"
          >取消</el-button
        >
      </div>
    </ht-drawer>
  </div>
</template>
<script lang="ts">
import HtHeader from '@/components/htHeader.vue';
import SelectTimeRange from '@/components/selectTimeRange.vue';
import { BreadType, Column, PageType } from 'htui-yllkbz/src/packages/type';
import { Component, Vue, Watch } from 'vue-property-decorator';
import Status from '@/components/status.vue';
import OldHtSearch from '@/components/oldHtSearch.vue';
import CreateProject from './createProject.vue';
import Detail from './detail.vue';
import Temp from '@/components/temp.vue';
import {
  MergeWareHouseApi,
  MergeWareHouseOrderDtlDto,
  MergeWareHouseOrderDto,
} from '@/plugins/api';
import { _axios } from 'vue-kst-auth';
interface State {
  /** 数据状态 */
  loading: boolean;
  searchHeight: number;
  filter: {
    keyWord: string | undefined;
    creatorId: string | undefined;
    status: boolean | undefined | any;
    creationTimeBegin: string | undefined;
    creationTimeEnd: string | undefined;
    isSort: boolean | undefined;
    timeArr: any;
    skipCount: number;
    maxResultCount: number;
    totalCount: number;
    currentPage: number;
  };
  dataSource: any;
  /** 批量选中的数据 */
  selectRow: any;
  selectRows: any[];
  visible: boolean;
  visible1: boolean;

  backTrackingData: any;
  // 并库状态
  options: any;
  options1: any;
}
@Component({
  components: {
    HtHeader,
    OldHtSearch,
    SelectTimeRange,
    Status,
    CreateProject,
    Detail,
    Temp,
  },
})
export default class Index extends Vue {
  MergeWareHouseApi = new MergeWareHouseApi('/alcohol-management', _axios);

  /** 数据 */
  state: State = {
    loading: false,
    searchHeight: 84,
    filter: {
      keyWord: '',
      creatorId: '',
      isSort: undefined,
      status: undefined,
      creationTimeBegin: '',
      creationTimeEnd: '',
      timeArr: [],
      skipCount: 0,

      maxResultCount: 20,
      currentPage: 1,
      totalCount: 0,
    },
    dataSource: [],
    /** 批量选中的数据 */
    selectRow: {},
    selectRows: [],
    visible: false,
    visible1: false,

    backTrackingData: {},
    options: [
      {
        value: 1,
        label: '未开始并库',
      },
      {
        value: 2,
        label: '并库执行中',
      },
      {
        value: 3,
        label: '已完成并库',
      },
    ],
    options1: [
      {
        value: true,
        label: '按序执行',
      },
      {
        value: false,
        label: '不限制',
      },
    ],
  };
  /** 生命周期 */
  mounted() {
    this.getDataSource();
  }

  //结束并库
  finish(val: any) {
    this.MergeWareHouseApi.complate2(val.id).then(() => {
      //
      this.$notify.success('操作成功');
    });
  }

  //保存
  save() {
    const data = (this.$refs.createProject as any).state.dataSource;

    if (!data.length) {
      this.$notify.error('未选择酒罐');

      return;
    }

    data.forEach((element: any, index: number) => {
      element.sortNo = index;
      element.weight = Number(element.weight);
    });

    const dtls = data.map((item: MergeWareHouseOrderDtlDto) => {
      return MergeWareHouseOrderDtlDto.fromJS(item);
    });

    const body = new MergeWareHouseOrderDto({
      orderNo: 'string',
      status: 1,
      isSort: (this.$refs.createProject as any).state.value,
      dtls,
    });

    this.MergeWareHouseApi.save2(body).then(() => {
      //
      this.$notify.success('操作成功');
      this.state.visible = false;
      this.getDataSource();
    });
  }

  /** 方法 */
  handClick() {
    //
  }
  //分页
  changePage(data: PageType) {
    this.state.filter.currentPage = data.currentPage;
    this.state.filter.maxResultCount = data.maxResultCount;
    this.state.filter.skipCount = data.skipCount;
    this.getDataSource();
  }
  /** 重置 */
  reset() {
    const { filter } = this.state;
    filter.keyWord = '';
    filter.creatorId = '';
    filter.isSort = undefined;
    filter.status = undefined;
    filter.timeArr = '';
    // filter.isEnabled = undefined;
    this.handleSearch();
  }
  /** 搜索的回调 */
  search(data: any) {
    this.state.filter.keyWord = data.keys;

    this.handleSearch();
  }
  // 点击进入详情
  handDetail(val: any) {
    this.state.visible1 = true;
    this.state.selectRow = val;
  }
  handleSearch() {
    this.state.filter.skipCount = 0;
    this.state.filter.currentPage = 1;

    if (this.state.filter.timeArr?.length) {
      this.state.filter.creationTimeBegin = this.state.filter.timeArr[0];
      this.state.filter.creationTimeEnd = this.state.filter.timeArr[1];
    } else {
      this.state.filter.creationTimeBegin = '';
      this.state.filter.creationTimeEnd = '';
    }

    this.getDataSource();
  }
  /** 查询列表 */
  getDataSource() {
    this.state.loading = true;
    const { filter } = this.state;

    this.MergeWareHouseApi.getList3(
      filter.keyWord,
      filter.creatorId,

      filter.creationTimeBegin,
      filter.creationTimeEnd,
      filter.status,
      filter.isSort,

      filter.skipCount,
      filter.maxResultCount
    )
      .then((res: any) => {
        this.state.dataSource = res.items || [];

        this.state.filter.totalCount = res.totalCount || 0;
      })
      .finally(() => {
        this.state.loading = false;
      });
  }
  handelVisible(height: number) {
    this.state.searchHeight = height;
  }
  /** 监听 */
  @Watch('state.filter.timeArr', { immediate: true })
  changeTimeArr(val: any) {
    if (!val) {
      this.state.filter.timeArr = [];
      this.state.filter.creationTimeBegin = '';
      this.state.filter.creationTimeEnd = '';
      // this.handleSearch();
    }
  }

  get columns(): Column[] {
    return [
      { key: 'orderNo', title: '并库计划单号' },
      { key: 'creatorId', title: '创建人' },
      //
      { key: 'creationTime', title: '创建时间' },
      { key: 'isSortStr', title: '并库执行顺序' },

      { key: 'statusStr', title: '并库状态' },
      { key: 'progress', title: '并库进度' },
      //

      //

      { key: 'handel', title: '操作' },
    ];
  }

  /** 计算属性 */
  get breadData(): BreadType[] {
    return [
      { key: 'k1', title: '库存业务管理' },
      { key: 'k2', title: '并库' },
    ];
  }

  get status() {
    return [
      { title: '未开始并库', key: 0, color: '#E2B236' },
      { title: '并库执行中', key: 1, color: 'var(--primary)' },
      { title: '已关闭并库', key: 2, color: '#CACECB' },
    ];
  }
}
</script>
<style lang="scss" scoped>
.cursor {
  color: var(--primary);
  cursor: pointer;
}
</style>
